<template>
<div class="login">
    <el-form
    ref="loginFormRef"
    style="max-width: 600px"
    :model="loginForm"
    status-icon
    :rules="rules"
    label-width="auto"
    class="login-form"
  >
  <h3 style="margin-top: 0px;">个人博客</h3>
    <el-form-item  prop="username">
      <el-input v-model="loginForm.username" type="text" autocomplete="off" placeholder="请输入账号" :prefix-icon="User" />
    </el-form-item>
    <el-form-item  prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        autocomplete="off"
        placeholder="请输入密码"
        :prefix-icon="Lock"
      />
    </el-form-item>
    <el-form-item  prop="code">
      <el-input v-model.number="loginForm.code" :prefix-icon="CircleCheck" style="width: 60%;" @keyup.enter.native="submitForm(loginFormRef)"/>
      <div class="login-code">
        <img :src="codeImg" @click="changeImg">
      </div>
    </el-form-item>
    <el-form-item>
      <div class="remmerberandQR">
        <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
        <div class="QR">
          <!-- <el-text class="mx-1" type="primary" @mouseover="toggleQrCode"  @mouseleave="toggleQrCode">扫码登录</el-text>
            -->
          <div class="scan">扫码登陆</div>
          <div class="popQR"></div>
        </div>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(loginFormRef)" style="width: 100%;" :loading="isLoading">
        <span v-if="!isLoading">登录</span>
        <span v-else>...</span>
      </el-button>
    </el-form-item>
  </el-form>
  <div class="footer">
    <el-text class="mx-1" type="warning" size="large">欢迎您的到来！今天是:{{nowTime}}</el-text>
    </div>
</div>
</template>

<script lang="ts" setup>
import {ref,reactive, onMounted, onBeforeUnmount} from 'vue'
import { userInfo, } from '@/types/user.ts'
import { FormInstance,  FormRules } from 'element-plus';
import { User,Lock,CircleCheck} from '@element-plus/icons-vue'
import {login,getCode} from '@/api/login.ts'
import { loginRes ,loginSuccess} from '@/api/response/loginResponse.ts'
import { useRouter } from 'vue-router';
import Cookies from 'js-cookie';
const router=useRouter()
const isLoading=ref(false);//加载
const codeImg=ref("")//验证码base64字符串
const captchaEnabled=ref(true)//验证码开关
const loginFormRef=ref<FormInstance>();
const loginForm=reactive<userInfo>({
    username:'admin',
    password:'admin123',
    code:'',
    uuid:'',
    rememberMe:false
})

const timer=ref()
const nowTime=ref('')
const getTime=()=>{
  const dayNames=new Array('星期日','星期一','星期二','星期三','星期四','星期五','星期六')
  const date=new Date();
  // nowTime.value=" "+date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日  "+dayNames[date.getDay()]+date.getHours()+":"+date.getMinutes()+":"+(date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds())
  nowTime.value=" "+date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日  "+dayNames[date.getDay()]+date.toLocaleTimeString()
}

//校验规则
const rules=reactive<FormRules<typeof loginForm>>({
    username:[{
        required:true,message:'请输入账号',trigger:'blur'
    }],
    password:[{
        required:true,message:'请输入密码',trigger:'blur'
    }],
    code:[{
        required:true,message:'请输入验证码',trigger:'blur'
    }]
})

const submitForm=(formEL:FormInstance | undefined)=>{
    if(!formEL) return 
    formEL?.validate((isValid:boolean,invalidateFilds:string)=>{
        if(isValid){
            //登录操作
            isLoading.value=true
            login(loginForm).then((res:loginSuccess)=>{
                console.log(res)
                //写入Cookie
                if(loginForm.rememberMe){
                Cookies.set('username',loginForm.username,{expires:30});
                Cookies.set('password',loginForm.password,{expires:30});
                Cookies.set('rememberMe',loginForm.rememberMe,{expires:30});
                }else{
                  Cookies.remove('username')
                  Cookies.remove('password')
                  Cookies.remove('rememberMe')
                }
                router.push('/home')
            }).catch(()=>{
              isLoading.value=false
            //刷新验证码
            if(captchaEnabled.value)
              initCode();
            })
        }else{
            console.log(invalidateFilds);
        }
    })
}

//获取验证码
const initCode=()=>{
  getCode().then((res:loginRes)=>{
    captchaEnabled.value=res.captchaEnabled??true
    if(captchaEnabled.value){
    codeImg.value="data:image/gif;base64,"+res.img
    loginForm.uuid=res.uuid
    }
  })
}

const changeImg=()=>{
  initCode()
}

const getCookie=()=>{
  loginForm.username=Cookies.get('username')??''
  loginForm.password=Cookies.get('password')??''
  loginForm.rememberMe=Boolean(Cookies.get('rememberMe'))??false
}

onMounted(()=>{
  initCode()
  getCookie()
  timer.value=setInterval(getTime,1000);
})

onBeforeUnmount(()=>{
  clearInterval(timer.value)
})
</script>

<style scoped lang="scss">
 @import '@/pages/Login.scss'
</style>